package com.wjt.homestayms.interceptor;

import com.wjt.homestayms.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过Session对象获取Session域中的loginUser对象。
        HttpSession session = request.getSession();
        User loginUser = (User)session.getAttribute("user");

        //判断loginUser对象是否为空
        if(loginUser != null){
            //放行
            return  true;
        }
        //如果login为空，拦截住设置错误信息并跳转到loginPage,
        session.setAttribute("msg","请先登录");
        response.sendRedirect("/");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
